📌 之前我們學過「陣列」可以放一堆數字,現在,我們也可以用「陣列」放一堆物件
一間班級有很多學生,每個學生都是一個物件,用陣列就能一次管理
#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    void setData(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void display() 
	    {
	        cout << "姓名: " << name;
	        cout << ", 年齡: " << age << endl;
	    }
};
int main() 
{
    Student students[2]; 
    students[0].setData("小A", 12);
    students[1].setData("小B", 13);
    for (int i = 0; i < 2; i++) 
    {
        students[i].display();
    }
    return 0;
}
📌 函式的參數不只能傳整數、字串,也可以傳物件
複製一份物件給函式
#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    Student(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void display() 
	    {
	        cout << "姓名: " << name << ", 年齡: " << age << endl;
	    }
};
void show(Student s) 
{
    s.display();
}
int main() 
{
    Student s1("小A", 12);
    show(s1);  
    return 0;
}
把原本的物件交給函式操作
#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    Student(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void display() 
	    {
	        cout << "姓名: " << name; 
	        cout << ", 年齡: " << age << endl;
	    }
	    void growUp() 
	    {
	        age++;
	    }
};
void birthday(Student &s) 
{
    s.growUp();
}
void show(Student s) 
{
    s.display();
}
int main() 
{
    Student s1("小A", 12);
    birthday(s1); 
    show(s1);
    return 0;
}
物件陣列讓我們能同時管理多個物件
就像一個班級管理許多學生
而物件傳遞則讓我們可以把物件交給函式處理
在傳遞時,要注意是傳值還是傳參考
這會決定物件是否真的被修改
傳值像是交出一份影印本,改了也不會影響原本的物件
傳參考則像是直接拿到正本,改了就會影響原始物件